package com.lazyframework.security.web.authentication.provider;

import com.lazyframework.security.web.authentication.UserDetails;
import com.lazyframework.security.web.authentication.UserDetailsService;
import com.lazyframework.security.web.authentication.token.Authentication;
import com.lazyframework.security.web.exception.AuthenticationException;
import com.lazyframework.security.web.exception.UserDisabledException;

/**
 * Abstract authentication provider, mainly charge check user status.
 *
 * @author maoning
 */
public abstract class AbstractAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected UserDetailsService userDetailsService() {
        return this.userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取认证信息
        Authentication auth = doAuthenticate(authentication);

        UserDetails userDetails = (UserDetails) auth.principal();

        // 检查用户状态
        if (!userDetails.isEnabled()) {
            throw new UserDisabledException();
        }

        return auth;
    }

    protected abstract Authentication doAuthenticate(Authentication authentication)
            throws AuthenticationException;

}
